import React from 'react';
import { Form, Modal, message } from 'antd';
import { FormCom, withReduxListener } from '{{relativePath}}../../../../components/index';
import asyncManage from '{{relativePath}}../../../../utils/asyncManage';
import { MODAL_CODE } from '../../constants';

function FormModal(props) {
  const { form, closeModalAction, refreshList } = props;
  const payload = props.modal[MODAL_CODE];

  // 关闭弹窗
  const onCancel = () => {
    closeModalAction(MODAL_CODE);
    form.setFieldsValue({});
  };

  // 提交
  const onOk = () => {
    form.validateFields(async (err, values) => {
      if (err) return;
      const { data, type } = payload;
      const isEdit = type === 'edit';
      const params = values;
      if (isEdit) {
        params.id = data.id;
      }
      const res = await asyncManage[isEdit ? 'user_update' : 'user_create'](params);
      if (res.code === 200) {
        message.success(isEdit ? '修改成功' : '添加成功');
        refreshList();
        onCancel();
      }
    });
  };

  const initFormData = _.get(payload, 'data', {});

  const commonConfig = {
    colLayout: {
      span: 24
    }
  };
  const formConfig = [
    {
      type: 'input',
      fieldName: 'name',
      label: '用户名',
      formItemProps: {
        rules: [{ required: true, message: '请填写用户名!' }]
      }
    },
    {
      type: 'text',
      fieldName: 'description',
      label: '描述',
      fieldProps: {
        rows: 4
      }
    }
  ].map(item => ({ ...item, ...commonConfig }));

  return (
    <Modal
      visible={!_.isEmpty(payload)}
      onCancel={onCancel}
      onOk={onOk}
      title={payload?.type === 'edit' ? '修改用户' : '添加用户'}
      okText="确认"
      cancelText="取消"
      className="clear-custom-width"
      width={600}
      maskClosable={false}
      destroyOnClose
    >
      <FormCom form={form} formData={initFormData} formConfig={formConfig} />
    </Modal>
  );
}
export default withReduxListener()(Form.create()(FormModal));
